package com.njcb.ams.store.page;

import java.util.Optional;

import com.njcb.ams.pojo.bo.Head;
import com.njcb.ams.pojo.dto.standard.PageQuery;
import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.util.AmsAssert;

/**
 * @version 1.1
 * @author liuyanlong
 *
 */
public class PageHandle {

	/**
	 * 分页一次，会在紧跟此语句的下一次数据查询时分页
	 * @return
	 */
	public static Page pageOnce(){
		Page page = PageHandle.getPlatformPage();
		if (null == page) {
			return page;
		}
		page.open(true);
		return page;
	}

	public static Page setTotal(){
		Page page = PageHandle.getPlatformPage();
		if (null == page) {
			return page;
		}
		page.setTotal(true);
		return page;
	}
	
	/**
	 * 开始分页
	 * 
	 * @param pageNum
	 * @param pageSize
	 */
	public static Page startPage(String pageNum, String pageSize) {
		AmsAssert.isInteger(pageNum,"当前页数必输为数字");
		AmsAssert.isInteger(pageSize,"每页条数必输为数字");
		return startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
	}

	/**
	 * 开始分页
	 */
	public static Page startPage() {
		Head requestHead = DataBus.getObject(Head.class);
		Page page = new Page(requestHead.getPage(), requestHead.getRows());
		return startPage(page);
	}

	/**
	 * 开始分页
	 * 
	 * @param pageNum
	 * @param pageSize
	 */
	public static Page startPage(int pageNum, int pageSize) {
		Page page = new Page(pageNum, pageSize);
		return startPage(page);
	}
	
	/**
	 * 开始分页
	 */
	public static Page startPage(PageQuery pageQuery) {
		Page page = new Page(pageQuery.getPage(), pageQuery.getRows());
		return startPage(page);
	}

	/**
	 * 开始分页
	 * @param page
	 */
	public static Page startPage(Page page) {
		if(null == page){
			return page;
		}
		Head head = DataBus.getObject(Head.class);
		if(null != head && SysBaseDefine.QUERY_MODEL_EXPALL.equals(head.getModel())){
			page.setPage(DataBus.getObject(Head.class).getPage());
			page.setRows(DataBus.getObject(Head.class).getRows());
		}
		page = new Page(page.getPage(), page.getRows());
		if (null == DataBus.getUncheckInstance()) {
			DataBus globalInfo = new DataBus();
			globalInfo.setPage(page);
			DataBus.setCurrentInstance(globalInfo);
		}
		DataBus.getUncheckInstance().setPage(page);
		return page;
	}

	/**
	 * 结束时移除Page
	 * 
	 * @return
	 */
	public static Page endPage() {
		Page page = getPlatformPage();
		page = Optional.ofNullable(page).orElse(page = new Page(0, 0));
		removePage();
		return page;
	}

	public static Page getPlatformPage() {
		if (null == DataBus.getUncheckInstance()) {
			return null;
		}
		Page page = DataBus.getUncheckInstance().getPage();
		return page;
	}

	public static Page getResultPage() {
		if (null == DataBus.getUncheckInstance()) {
			return null;
		}
		return DataBus.getUncheckInstance().getResultPage();
	}
	
	private static void removePage() {
		if (null != DataBus.getUncheckInstance()) {
			DataBus globalInfo = DataBus.getUncheckInstance();
			globalInfo.setResultPage(globalInfo.getPage());
			globalInfo.setPage(null);
		}
	}

}
